package jfuzzyprincepless.algorithm.structure;

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

import jfuzzyprincepless.agents.INegotiatingAgent;
import jfuzzyprincepless.negotiation.INegotiationContext;
import jfuzzyprincepless.negotiation.services.IAgentsListService;
import jfuzzyprincepless.negotiation.services.impl.AgentsListService;

public class ElementsAsAgentsNegotiationFor
	extends DefaultNegConstruction
	implements INegotiationFor, INegotiationConstruction,
		INegotiatingAgent
{
	private IContext2forAgents context2forAgents;

	public ElementsAsAgentsNegotiationFor(
		IContext2forAgents context2forAgents
	) {
		this.context2forAgents = context2forAgents;
		agList = new AgentsListService(
			Arrays.<INegotiatingAgent>asList(this)
		);
	}

	@Override
	public boolean negotiate(INegotiationContext context) {
		return false;
	}

	@Override
	public void onNegotiationStart(
		INegotiationContext context
	) {
		ArrayList<INegotiatingAgent> resultAgents =
			new ArrayList<INegotiatingAgent>();
		resultAgents.addAll(
			context.getService(IAgentsListService.class)
				.getAgentsList()
		);
		resultAgents.remove(this);// XXX: performance

		List<INegotiatingAgent> additAgents =
			context2forAgents.getAgents(context);
		resultAgents.addAll(additAgents);

		context.registerService(
			new AgentsListService(resultAgents)
		);

		for (INegotiatingAgent cfag : additAgents) {
			cfag.onNegotiationStart(context);
		}
	}

	@Override
	public String toString() {
		return "ElementsAsAgentsNegotiationFor";
	}

	public void setContext2forAgents(
		IContext2forAgents context2forAgents
	) {
		this.context2forAgents = context2forAgents;
	}
}
